package com.scau.yangsuiyu.estore.dababases.dao;

import com.scau.yangsuiyu.estore.dababases.entity.DeliveryAddress;
import com.scau.yangsuiyu.estore.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * @author suiyu_yang
 * @description 收货地址的Dao类
 * @date 2019-06-09 11:39
 * @email suiyu_yang@163.com
 */
public class DeliveryAddressDao {

    public void insert(DeliveryAddress deliveryAddress) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.save(deliveryAddress);

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public void delete(DeliveryAddress deliveryAddress) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.delete(deliveryAddress);

        transaction.commit();
        HibernateUtil.closeSession();

    }

    public void update(DeliveryAddress deliveryAddress) {
        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.beginTransaction();

        session.update(deliveryAddress);

        //当事务提交时，hibernate会自动按照一定的策略将session中的持久化对象，同步到数据库中，从而自动使数据库的状态和session中的对象状态完全一致。
        // 如果要在事务提交前同步，则可以使用session的flush方法。
        session.flush();

        transaction.commit();
        HibernateUtil.closeSession();
    }

    public DeliveryAddress getSellerByPhone(String id) {
        Session session = HibernateUtil.currentSession();

        String sql = "from DeliveryAddress deliveryAddress where deliveryAddress.id = '" + id + "' ";

        DeliveryAddress deliveryAddress = (DeliveryAddress) session.createQuery(sql).uniqueResult();
        HibernateUtil.closeSession();
        return deliveryAddress;
    }
}
